package appLog

import (
	"fmt"
	"go.uber.org/zap"
	"os"
	"sync"
	"time"
	"zhou_gin_api/utils"
)

type myLog struct {
	logger *zap.Logger
}

const LogDir = "storage/logs/"

var log *zap.Logger
var mux sync.Mutex
var today string

func InfoSimpleLog(msg interface{}) {
	setFileLog()
	sugar := log.Sugar()
	defer sugar.Sync()

	sugar.Info(msg)
	//log.Info(msg)
}

func ErrorSimpleLog(msg interface{}) {
	setFileLog()
	sugar := log.Sugar()
	defer sugar.Sync()

	sugar.Error(msg)
}

func InfoLog(msg string, anyone ...interface{}) {
	setFileLog()
	sugar := log.Sugar()
	defer sugar.Sync()

	sugar.Info(msg, anyone)
}

func ErrorLog(msg string, anyone interface{}) {
	setFileLog()
	sugar := log.Sugar()
	defer sugar.Sync()

	sugar.Error(msg, anyone)
}

//设置今日的文件名
func setFileLog() {

	mux.Lock()
	defer mux.Unlock()

	newtoday := time.Now().Format("2006-01-02")

	if newtoday != today {

		today = newtoday
		cfg := zap.NewDevelopmentConfig()
		cfg.OutputPaths = []string{
			LogDir + today + "_golang.log",
		}
		var err error
		log, err = cfg.Build()
		if err != nil {
			panic(err)
		}
	}

}

func init() {

	newtoday := time.Now().Format("2006-01-02")
	today = newtoday
	cfg := zap.NewDevelopmentConfig()
	cfg.OutputPaths = []string{
		LogDir + today + "_golang.log",
	}
	var err error
	log, err = cfg.Build()
	if err != nil {
		panic(err)
	}

}

func GetMyLog(filename string) *myLog {

	newtoday := time.Now().Format("2006-01-02")
	cfg := zap.NewDevelopmentConfig()

	dir := LogDir + newtoday
	exists, _ := utils.PathExists(dir)
	if !exists {
		os.Mkdir(dir, os.ModePerm)
	}

	cfg.OutputPaths = []string{
		LogDir + newtoday + "/" + filename + "-" + newtoday + ".log",
	}
	log, err := cfg.Build()
	if err != nil {
		fmt.Println("创建文件出错?", err.Error())
	}

	return &myLog{
		logger: log,
	}
}

func (mylog *myLog) Info(args ...interface{}) {

	sugar := mylog.logger.Sugar()
	defer sugar.Sync()

	sugar.Info(args)
}
